# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :Common.py
# @Time      :2022/3/12 0:28
# @Author    :Yongbo Zhou
import re

# 字符串每两位进行切分
from datetime import datetime


def hex_str_split(hex_str):
    return re.sub(r"(?<=\w)(?=(?:\w\w)+$)", " ", hex_str)


# 是否包含标志性 字符
def include_char(scan_str, flag):
    return flag in scan_str
    pass


# 将16进制数据转换为ascii 码值
def hex_ascii(hex_arr: list[str] = []):
    return ''.join((chr(int(hex, 16))) for hex in hex_arr)
    pass


def hex_byte(hex):
    return int(hex, 16).to_bytes(length=1, byteorder='big', signed=True)[0]


# 将16进制数据转换为int数据
def hex_int(hex_arr: list[str] = []):
    return int(''.join((hex) for hex in hex_arr), 16)


# word类型转 int类型
def hex_word_int(hex_arr: list[str] = []):
    return hex_byte(hex_arr[0]) << 8 | hex_byte(hex_arr[1])


# word类型转 int类型
def hex_word_int_l(hex_arr: list[str] = []):
    return hex_byte(hex_arr[1]) << 8 | hex_byte(hex_arr[0])


# dword类型转 int类型
def hex_dword_int(hex_arr: list[str] = []):
    return hex_byte(hex_arr[0]) << 24 | hex_byte(hex_arr[1]) << 16 | hex_byte(hex_arr[2]) << 8 | hex_byte(hex_arr[3])


# 计算校验码的位置
def check_code_index(hex_arr: list[str] = [], *args, **kwargs) -> int:
    return len(hex_arr) - 1


# 6字节转时间
def hex_date_6(hex_arr: list[str] = [], *args, **kwargs) -> str:
    return datetime(int('20' + str(hex_int(hex_arr[0])).zfill(2)), hex_int(hex_arr[1]), hex_int(hex_arr[2]),
                    hex_int(hex_arr[3]),
                    hex_int(hex_arr[4]), hex_int(hex_arr[5])).strftime("%Y-%m-%d %H:%M:%S")


def offset(*args, **kwargs):
    return list(kwargs['r_p_dict'].items())[len(kwargs['r_p_dict'].items()) - 1][1][1]


def offset_r_1(*args, **kwargs):
    return list(kwargs['r_p_dict'].items())[len(kwargs['r_p_dict'].items()) - 1][1][1] + 1


def offset_r_2(*args, **kwargs):
    return list(kwargs['r_p_dict'].items())[len(kwargs['r_p_dict'].items()) - 1][1][1] + 2


def bin_hex(bin_str: str):
    return ''.join(
        hex(int(bin_substr, 2))[2:] for bin_substr in re.sub(r"(?<=[01])(?=(?:[01]{4})+$)", " ", bin_str).split(' '))


def code_list(name, len, *args, **kwargs):
    offset_ = offset(*args, **kwargs)
    num = kwargs['heard'].__dict__[name]
    if num == 0:
        kwargs['r_p_dict'][kwargs['fieldName']] = offset_, offset_, None
        return offset_, offset_, None
    else:
        start_index = offset_ + 1
        end_index = offset_ + len * num
        ret = '__' + '__'.join(
            [str(hex_int(args[0][index:index + len])) for index in range(start_index, end_index, len)])
        kwargs['r_p_dict'][kwargs['fieldName']] = start_index, end_index, ret
        return start_index, end_index, ret


if __name__ == '__main__':
    # print(hex_word_int(['1f', '2f']))
    # ret = [str(index)for index in range(109, 112, 4)]
    # print(ret)
    # print(''.join(ret))
    bin_str = '0100100100110100101010'
    print(bin_hex(bin_str))
    pass
